#!/usr/bin/python

import codecs
import random
from lettermapping import letterMapping
import sys
sys.path.append("../")
import scriptgoodies

def main(env):
	manPict = env["static"]["cwHangman_manPict"].split("\n")
	manPict[2:2] = [env["static"]["cwHangman_manPatternPict"]]*int(env["prefs"]["cwHangman_ropeLength"])
	gibbetPict = env["static"]["cwHangman_gibbetPict"].split("\n")
	gibbetPict[2:2] = [env["static"]["cwHangman_gibbetPatternPict"]]*int(env["prefs"]["cwHangman_ropeLength"])
	message = []
	directives = []
	if env["context"]["selection"] == "":
		secrets = codecs.open("%s_%s.txt" % (env["constants"]["language"],env["prefs"]["cwHangman_level"]),"r","utf8").read().split("\n")
		env["private"]["cwHangman_secret"] = letterMapping[random.choice(secrets)]
		guessed = env["private"]["cwHangman_secret"][0] + "-" * (len(env["private"]["cwHangman_secret"])-2) + env["private"]["cwHangman_secret"][-1]
		remaining = len(manPict)-2
		directives = [("updatePrefs",scriptgoodies.setTemporaryPrefs(env,{
				"editorFontFamily": env["constants"]["outputDialogFontFamily"],
				"shortTermAdaptationDeleteOnQuit": False, # hidden preference. Do not save.
				"keyboardOrder": "3static",
				"progressiveMode": False,
				"scannerName": "sisyphus"
			})
		)]
	else:
		if env["meta"]["poorSuffix"] == "" or "cwHangman_secret" not in env["private"]:
			return [("replace",""),("updatePrefs",scriptgoodies.restoreBackupPrefs(env))]
		guessed = env["context"]["selection"].split("\n")[1]
		remaining = sum(1 for (x,y) in zip(env["context"]["selection"].split("\n")[2:],gibbetPict) if x==y)-2
		for letter in env["meta"]["poorSuffix"]:
			newGuessed = "".join([(cs if cs == letter else cg) for (cs,cg) in zip(env["private"]["cwHangman_secret"],guessed)])
			remaining -= (1 if guessed == newGuessed else 0)
			guessed = newGuessed
			if guessed == env["private"]["cwHangman_secret"] or remaining == 0:
				message = [(env["static"]["cwHangman_successMessage"] if guessed == env["private"]["cwHangman_secret"] else env["static"]["cwHangman_failureMessage"] % env["private"]["cwHangman_secret"])]
				del env["private"]["cwHangman_secret"]
				break
	newBoard = [guessed]
	newBoard.extend(manPict[:len(manPict)-remaining-1])
	newBoard.extend(gibbetPict[len(gibbetPict)-remaining-1:])
	newBoard.extend(message)
	text = "(=\n%s\n)" % "\n".join(newBoard)
	return [
		("replace", env["meta"]["name"]+text),
		("moveCursor", -len(text))
	] + directives
